package io.renren.socket;

import java.math.BigInteger;
import java.util.List;

import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import io.renren.common.utils.StringUtils;
import io.renren.modules.substation.controller.TInfoBackupConfigController;
import org.msgpack.MessagePack;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 解码器
 * @author Administrator
 *
 */
public class MsgPckDecode extends MessageToMessageDecoder<ByteBuf>{

    private static Logger logger = LoggerFactory.getLogger(TInfoBackupConfigController.class);

    private ByteBuf header;

    public MsgPckDecode(){
        logger.debug("-------------------MsgPckDecode header----------------");
        byte[] head=new byte[]{(byte)0xFF,(byte)0xFF,(byte)0xFF,(byte)0xFF} ;// 十六进制是 [0x50,0x50,0x50,0x50]
        this.header = Unpooled.copiedBuffer(head);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg,
                          List<Object> out) throws Exception {
        String str = "";
        String hexStr = "";

        ByteBuf msgHead = decodeHead(msg);
        if(msg.hasArray()) { // 处理堆缓冲区
            str = new String(msg.array(), msg.arrayOffset() + msg.readerIndex(), msg.readableBytes());
        } else if(msgHead != null) { // 处理直接缓冲区以及复合缓冲区
            byte[] bytes = new byte[msgHead.readableBytes()];
            msgHead.getBytes(msgHead.readerIndex(), bytes);
//            hexStr = new String(bytes, "UTF-8");
            hexStr = StringUtils.bytesToHexString(bytes);
            //logger.debug("hexStr:" + hexStr);

            MessagePack pack = new MessagePack();
            out.add(hexStr);
        }
//        logger.debug("接收到消息:" + str);
//        logger.debug("接收到消息Hex字符串:" + hexStr);
    }

    /***
      * 利用帧头和帧尾取出数据帧，过滤帧头前无效数据，过滤没有帧头和帧尾的数据。
      * @param  buf:字节缓冲区
      * @return ByteBuf:数据帧（去掉帧头和帧尾）
      * 
      * 
      *  */
    protected ByteBuf decodeHead(ByteBuf buf) {
        // 帧头起始位置
        int sliceStart = 0;
//        // 帧尾起始位置
//        int sliceEnd = 0;
        // 数据帧
        ByteBuf frame = null;
        // 帧头是存在
        if (header != null) {
            // 获取帧头位置
            int index = ByteBufUtil.indexOf(header, buf);
            // 帧头第一次出现位置找到
            if (index > -1 && index < buf.capacity()) {
                // 舍弃帧头前面的数据
                buf.readerIndex(index);
                // 将帧头位置保存
                sliceStart = index;

                byte[] bytes = new byte[8];
                buf.getBytes(buf.readerIndex(),bytes);
                String hexStr = StringUtils.bytesToHexString(bytes);
//                logger.debug("decodeHead - hexStr:" + hexStr);

                String hexLen = hexStr.substring(8,16);
                //解析长度
                BigInteger hexLen2 = new BigInteger(hexLen, 16);
                hexLen2 = hexLen2.multiply(new BigInteger("2"));
                int datalen = hexStr.substring(16).length();
                //计算长度
                BigInteger datalen2 = new BigInteger(String.valueOf(datalen));

                // 获取数据子帧
                frame = buf.slice(sliceStart, buf.readableBytes());
                // 将reader索引设定到帧尾的后面
                buf.skipBytes(datalen);
                // 将数据帧返回
                return frame;
            }
        }
        return null;
    }
}

